require 'models/account'
require 'network/state_handler'

class LogonHandler
  include StateHandler

  def initialize(connection, parent_handler)
    @parent_handler = parent_handler
    @connection = connection

    setup_states
    set_state :init

  end

  def handle(data)
    call_state data.sanitize
  end


  def setup_states
  puts "setup"
    add_state :init  do |data|
      @connection.send_data "Please enter your username or 'new' to create one: "
      set_state :get_username
    end

    add_state :get_username do |data|
      @username = data
      if @username =~ /new/
        @connection.send_data "Please enter the account name to create: "
        set_state:create_username
      else # not new.. aka regular login
        set_state :get_password
        @connection.send_data "Please enter your password: "
      end
    end

    add_state :get_password do |data|
      @password = data

      begin
        @connection.account = Account.validate(:username => @username, :password => @password)
        @@logger.info "#{@username} logged in"

        @parent_handler.push_handler :character_handler
        set_state :finished
        @connection.send_line "entering character mode... hit enter to continue..."
      rescue => err
        # not a valid account

        @connection.send_line err
        set_state:init

        @@logger.warn "#{@username} failed login"
        @username, @password = "", ""
      end

    end

    add_state :create_username do |data|
      @username = data
      @connection.send_data "please enter an account password: "
      set_state :create_password
    end

    add_state :create_password do |data|
      @password = data
      @connection.send_data "please confirm account password: "
      set_state :create_confirm_password
    end

    add_state :create_confirm_password do |data|
      if @password == data
        #create account
        begin
          @account = Account.new :username => @username, :password => @password, :email => "test"
          #load account into database
          @connection.account = @account
          @account_db.add @account

        rescue => err
          @connection.send_line err
          set_state :init
        end

      else
        @connection.send_line "passwords do not match"
        set_state :create_password
      end

    end

    add_state :finished do |data|
      @connection.send_line "you are logged in"
      if data.include? "quit"
        @connection.send_line "disconnecting you..."
        @connection.close
      end

    end

  end


end
